<template>
  <el-form ref="formRef" :model="formData"  label-position="top" :rules="rules" label-width="40px" :disabled="isDetail">
    <!-- 分供方清单上传 -->
    <el-divider content-position="left">分供方清单</el-divider>
    <el-form-item prop="subSupplierImageUrl">
      <UploadImgs
        @uploadedfilenames = "uploadedfilenamest"
        v-model="formData.trace.subSupplierImageUrls"
        :disabled="isDetail" />
    </el-form-item>
    <el-divider content-position="left">第三方检测报告<el-button @click="addThirdReportTableData" link type="primary">添加</el-button></el-divider>
      <el-form-item :disabled="isDetail">
        <el-table :data="thirdReportTableData" border style="width: 100%">
          <el-table-column label="序号" align="center" width="80">
            <template #default="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="thirdName" label="报告名称" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.name" prop="thirdName" size="small" :disabled="isDetail"/>
            </template>
          </el-table-column>
          <el-table-column prop="thirdDate" label="报告截止日期" align="center">
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.deadline"
                type="date"
                size="small"
                prop="thirdDate"
                placeholder="选择日期"
                style="width: 100%;"
              />
            </template>
          </el-table-column>
          <el-table-column prop="thirdImageUrls" label="上传图片" align="left" width="600">
            <template #default="scope">
              <UploadImgs height="80px" width="80px" @uploadedfilenames = "(fileNames, value) => uploadedThirdImageUrls(fileNames, value, scope.$index)" v-model="scope.row.imageUrls" :disabled="isDetail" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="62">
            <template #default="scope">
              <el-button @click="deleteThirdReportTableData(scope.row)" link type="primary">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
    </el-form-item>
    <el-divider content-position="left">生产视频 <el-button @click="addProductionVideoTableData" link type="primary">添加</el-button></el-divider>
    <el-form-item>
      <el-table :data="productionVideoTableData" border style="width: 100%">
        <el-table-column label="序号" align="center" width="80">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="videoName" label="生产视频名称" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.name" size="small"/>
          </template>
        </el-table-column>
        <el-table-column prop="videoUrls" label="上传视频" align="center" width="600">
          <template #default="scope">
<!--            <UploadVideo v-model="scope.row.videoUrls" @uploadedfilenames = "(fileNames, value) => uploadedVideoUrls(fileNames, value, scope.$index)" :disabled="isDetail" />-->
            <UploadFile
              :disabled="isDetail"
              v-model="scope.row.videoUrls"
              v-model:file-list="scope.row.videoUrls"
              :file-type="['mp4']"
              :limit="1"
              :update:modelValue="testVideo"
              class="min-w-80px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="videoCover" label="生产视频封面" align="center">
          <template #default="scope">
            <UploadImg v-model="scope.row.videoCover" :disabled="isDetail" width="80px" height="80px" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="62">
          <template #default="scope">
            <el-button @click="deleteProductionVideoTableData(scope.row)" link type="primary">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-divider content-position="left">生产记录 </el-divider>
    <el-form-item label="生产记录名称" prop="trace.productionRecordName">
      <el-input v-model="formData.trace.productionRecordName" placeholder="请输入生产记录名称"/>
    </el-form-item>
    <el-form-item>
      <el-form-item prop="productionRecordImageUrls1">
        <UploadImgs
          @uploadedfilenames = "uploadedProductionRecordImageUrls"
          v-model="formData.trace.productionRecordImageUrls"
          :disabled="isDetail" />
      </el-form-item>
    </el-form-item>
    <el-divider content-position="left">产品检验记录</el-divider>
    <el-form-item label="检验记录名称" prop="inspectionRecordNameTest">
      <el-input v-model="formData.trace.inspectionRecordName" placeholder="请输入检验记录名称" />
    </el-form-item>
    <el-form-item>
      <el-form-item prop="supplierListImage2">
        <UploadImgs
          @uploadedfilenames = "uploadedInspectionRecordImageUrls"
          v-model="formData.trace.inspectionRecordImageUrls"
          :disabled="isDetail" />
      </el-form-item>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { PropType, reactive } from "vue";
import { propTypes } from "@/utils/propTypes";
import {Spu} from "@/api/mall/product/spu";
import {copyValueToTarget} from "@/utils";

const message = useMessage()
const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => ({})
  },
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})

const formRef = ref() // 表单Ref

const formData = ref<Spu>({
  trace: {
    subSupplierImageUrls: [],
    inspectionRecordName: '', // 初始化检验记录名称
    inspectionRecordImageUrls: [] // 初始化检验记录图片数组
  },
  inspectionRecordName: ''
})

// 表单规则
const rules = reactive({
  //subSupplierImageUrl: [required],
  //supplierListImage: [{ required: false, message: '请上传分供方清单图片', trigger: 'change' }],
  //picUrl: [{ required: true, message: '请上传图片', trigger: 'change' }],
  thirdName: [required],
  thirdDate: [required],
  thirdImageUrls: [required],
  //productionRecordName: [required]
  //videoName: [required],
  //videoUrls: [required]
})

const uploadedfilenamest = (filenames: string[] , value: string[]) => {
  try {
    if (value) {
      formData.value.trace.subSupplierImageUrls = value;
    }
  } catch (error) {
    console.error(error)
  }
}

const uploadedProductionRecordImageUrls = (filenames: string[] , value: string[]) => {
  try {
    if (value) {
      formData.value.trace.productionRecordImageUrls = value;
    }
  } catch (error) {
    console.error(error)
  }
}

const uploadedInspectionRecordImageUrls = (filenames: string[] , value: string[]) => {
  try {
    if (value) {
      formData.value.trace.inspectionRecordImageUrls = value;
    }
  } catch (error) {
    console.error(error)
  }
}
// 上传视频的时候把url绑定到v-model
const uploadedThirdImageUrls = (fileNames: string[], value: string[], index: number) => {
  if (value) {
    thirdReportTableData.value[index].imageUrls = value
  }
}
// 上传视频的时候把url绑定到v-model,这里主要是用到了动态表格编辑
const uploadedVideoUrls = (fileNames: string[], value: string[], index: number) => {
  if (value) {
    productionVideoTableData.value[index].videoUrls = value
  }
}
// 第三方检测报告定义
const thirdReportTableData = ref([])

const productionVideoTableData = ref([])
// 第三方检测报告新增一行
const addThirdReportTableData = ()=>{
  const row = {
    name: null,
    date: null,
    imageUrls: null
  }
  thirdReportTableData.value.push(row)
}
// 生产视频新增行数
const addProductionVideoTableData = () =>{
  const row = {
    name: null,
    videoCover: null,
    videoUrls: null
  }
  productionVideoTableData.value.push(row)

}

const testVideo = () => {
  console.log("不要脸")
}
// 第三方检测报告删除
const deleteThirdReportTableData = (row) =>{
  const index = thirdReportTableData.value.indexOf(row);
  if (index !== -1) {
    thirdReportTableData.value.splice(index, 1);
  }
}
// 生产视频删除行
const deleteProductionVideoTableData = (row) =>{
  const index = productionVideoTableData.value.indexOf(row);
  if (index !== -1) {
    productionVideoTableData.value.splice(index, 1);
  }
}

watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return;
    }
    // 清空现有的表格数据
    thirdReportTableData.value = [];
    productionVideoTableData.value = []; // 清空生产视频表格数据
    // 处理第三方检测报告数据
    data.trace.thirdReportData?.forEach((item) => {
      const row = {
        traceId: item.traceId,
        id: item.id,
        name: item.name,
        deadline: item.deadline,
        imageUrls: item.thirdReportImageUrls // 确保这里的属性名与表格中的一致
      };
      thirdReportTableData.value.push(row);
    });

    // 处理生产视频数据
    data.trace.productionVideos?.forEach((item) => {
      const row = {
        traceId: item.traceId,
        id: item.id,
        name: item.name, // 确保这里的属性名与表格中的一致
        videoCover: item.videoCover,
        videoUrls: item.videoUrls
      };
      productionVideoTableData.value.push(row);
    });
    // 复制表单数据
    copyValueToTarget(formData.value, data);

  },
  {
    immediate: true
  }
);

const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    await unref(formRef)?.validate()
    // 校验通过更新数据
    Object.assign(props.propFormData, formData.value)

    // 第三方检测报告
    formData.value.trace.thirdReportData = thirdReportTableData.value
    // 生产视频
    formData.value.trace.productionVideos = productionVideoTableData.value
  } catch (e) {
    message.error('溯源信息不完善，请填写相关信息')
    emit('update:activeName', 'trace')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })
</script>
